import * as React from 'react';
import HoverMenu from 'material-ui-popup-state/HoverMenu';
import MenuItem from '@mui/material/MenuItem';
import ChevronRight from '@mui/icons-material/ChevronRight';
import { usePopupState, bindHover, bindFocus, bindMenu } from 'material-ui-popup-state/hooks';
import { IMenuItem } from './type';
import s from './index.module.scss';
import { Typography } from '@mui/material';

const CascadingContext = React.createContext({
  parentPopupState: null,
  rootPopupState: null
});

function CascadingMenuItem({ onClick, ...props }) {
  const { rootPopupState } = React.useContext(CascadingContext);
  if (!rootPopupState) throw new Error('must be used inside a CascadingMenu');
  const handleClick = React.useCallback(
    (event) => {
      rootPopupState.close(event);
      if (onClick) onClick(event);
    },
    [rootPopupState, onClick]
  );

  return <MenuItem {...props} onClick={handleClick} />;
}

function CascadingSubmenu({ title, popupId, ...props }) {
  const { parentPopupState } = React.useContext(CascadingContext);
  const popupState = usePopupState({
    popupId,
    variant: 'popover',
    parentPopupState
  });
  return (
    <>
      <MenuItem {...bindHover(popupState)} {...bindFocus(popupState)}>
        <Typography fontWeight="bold">{title}</Typography>
        <ChevronRight style={{ marginRight: '-10px' }} />
      </MenuItem>
      <CascadingMenu
        {...props}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'left' }}
        popupState={popupState}
      />
    </>
  );
}

function CascadingMenu({ popupState, ...props }) {
  const { rootPopupState } = React.useContext(CascadingContext);
  const context = React.useMemo(
    () => ({
      rootPopupState: rootPopupState || popupState,
      parentPopupState: popupState
    }),
    [rootPopupState, popupState]
  );

  return (
    <CascadingContext.Provider value={context}>
      <HoverMenu {...props} {...bindMenu(popupState)} />
    </CascadingContext.Provider>
  );
}

export interface IMenuItemProps {
  item: IMenuItem;
  itemClick?: (d: IMenuItem, index?: number) => void;
}
const Menu = (props: IMenuItemProps) => {
  const { item, itemClick } = props;
  const { name, value, isSelect, children = [] } = item;
  console.log('update Menu:', name);

  const popupState = usePopupState({
    popupId: 'menu_' + value,
    variant: 'popover'
  });
  function getNode(list: IMenuItem[]) {
    return list.map((v: IMenuItem) => {
      if (v.children?.length) {
        return (
          <CascadingSubmenu key={v.value} popupId={v.value + '_popup'} title={v.name}>
            {getNode(v.children)}
          </CascadingSubmenu>
        );
      }
      return (
        <CascadingMenuItem
          key={v.value}
          onClick={() => {
            itemClick(v);
          }}
        >
          <Typography fontWeight="bold">{v.name}</Typography>
        </CascadingMenuItem>
      );
    });
  }
  const childrenNode = getNode(children);
  return (
    <div>
      <div
        className={s.menuItem + ' ' + (isSelect ? s.selected : '')}
        {...bindHover(popupState)}
        {...bindFocus(popupState)}
      >
        {name}
      </div>
      <CascadingMenu
        popupState={popupState}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
        transformOrigin={{ vertical: 'top', horizontal: 'left' }}
      >
        {childrenNode}
      </CascadingMenu>
    </div>
  );
};

export default Menu;
